package net.huashitong.Project.service;

import jodd.util.StringUtil;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.service.NodeNewschedulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static net.huashitong.Project.util.HolidayUtils.getScheduleActiveDate;

/**
 * 节点过程的方法
 */
@Service
public class NodeProcessService {

    @Autowired
    private NewProjectsService nps;

    @Autowired
    private NodeNewschedulesService nns;

    //推算节点的计划时间
    public void updateNodeProcessDate(List<String> projectIds) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        for (String projectId : projectIds) {
            NewProjects newProjects = nps.getById(projectId);
            //节点启动时间（项目通过审核的时间）
            String nodeStartDate = newProjects.getPlanBeginDate();
            Map<String, String> nodeStartDateMap = new HashMap<>();     //节点开始时间
            Map<String, String> nodeEndDateMap = new HashMap<>();       //节点结束时间

            List<NodeNewschedules> nodeNewschedules = nns.getNodeByProjectId(projectId);
            Map<String, NodeNewschedules> openMap = nps.dealWithNodesMapByType(nodeNewschedules, "open");
            //nodeAndPreNodeMap = <节点id，前置节点id>
            Map<String, String> nodeAndPreNodeMap = new HashMap<>();
            for (Map.Entry<String, NodeNewschedules> entry : openMap.entrySet()) {
                NodeNewschedules node = entry.getValue();
                String preNodeId = node.getPreNodeId();
                String nodeId = entry.getKey();
                nodeAndPreNodeMap.put(nodeId, preNodeId);
                if ("#".equals(preNodeId)) {
                    //开始时间
                    nodeStartDateMap.put(nodeId, nodeStartDate);
                    //计划时间
                    String planTime = node.getPlanTime();
                    int planTime_int = Integer.parseInt(StringUtil.isBlank(planTime) ? "0" : planTime);
                    Date startDate_date = format.parse(nodeStartDate);
                    Date endDate_date = getScheduleActiveDate(startDate_date, new ArrayList<String>(), planTime_int);
                    String endDate = format.format(endDate_date);
                    //结束时间
                    nodeEndDateMap.put(nodeId, endDate);
                }
            }
            List<NodeNewschedules> bigNodeList = nns.getNodeInfo(projectId, "1", "", "1");
            for (NodeNewschedules v2 : bigNodeList) {
                for (NodeNewschedules v1 : bigNodeList) {
                    String nodeId = v1.getNodeId();
                    String preNodeId = v1.getPreNodeId();
                    if (!nodeEndDateMap.containsKey(nodeId)) {
                        if (preNodeId.contains(",")) {
                            String[] arr = preNodeId.split(",");
                            List<String> dateList = new ArrayList<>();
                            for (String s : arr) {
                                if (nodeEndDateMap.containsKey(s) || !nodeAndPreNodeMap.containsKey(s)) {
                                    if (nodeEndDateMap.containsKey(s)) {
                                        String newStartDate = nodeEndDateMap.get(s);
                                        dateList.add(newStartDate);
                                    }
                                } else {
                                    break;
                                }
                            }
                            if (dateList.size() == 0) {
                                continue;
                            }
                            String startDate = showLastDate(dateList);
                            nodeStartDateMap.put(nodeId, startDate);
                            //==============================================================
                            String planTime = v1.getPlanTime();
                            int planTime_int = Integer.parseInt(StringUtil.isBlank(planTime) ? "0" : planTime);
                            Date startDate_date = format.parse(startDate);
                            Date endDate_date = getScheduleActiveDate(startDate_date, new ArrayList<String>(), planTime_int);
                            String endDate = format.format(endDate_date);
                            //==============================================================
                            nodeEndDateMap.put(nodeId, endDate);
                        } else {
                            List<String> dateList = new ArrayList<>();
                            if (nodeEndDateMap.containsKey(preNodeId) || !nodeAndPreNodeMap.containsKey(preNodeId)) {
                                if (nodeEndDateMap.containsKey(preNodeId)) {
                                    String newStartDate = nodeEndDateMap.get(preNodeId);
                                    dateList.add(newStartDate);
                                }
                                if (dateList.size() == 0) {
                                    continue;
                                }
                                String startDate = showLastDate(dateList);
                                nodeStartDateMap.put(nodeId, startDate);
                                //==============================================================
                                String planTime = v1.getPlanTime();
                                int planTime_int = Integer.parseInt(StringUtil.isBlank(planTime) ? "0" : planTime);
                                Date startDate_date = format.parse(startDate);
                                Date endDate_date = getScheduleActiveDate(startDate_date, new ArrayList<String>(), planTime_int);
                                String endDate = format.format(endDate_date);
                                //==============================================================
                                nodeEndDateMap.put(nodeId, endDate);
                            }
                        }
                    }
                }
            }
            //更新初始计划时间
            for (NodeNewschedules v1 : bigNodeList) {
                String nodeId = v1.getNodeId();
                if (nodeEndDateMap.containsKey(nodeId) && nodeStartDateMap.containsKey(nodeId)) {
                    String startDate = nodeStartDateMap.get(nodeId);
                    String endDate = nodeEndDateMap.get(nodeId);
                    v1.setNodePlanStartDate(startDate);
                    v1.setNodePlanEndDate(endDate);
                }
            }
            nns.batchUpdate(bigNodeList);
            System.out.println(newProjects.getName() + "--更新成功！");
        }
        System.out.println("ok!");
    }

    /**
     * 查找最后面的日期
     *
     * @param dateArray
     * @return
     * @throws ParseException
     */
    public String showLastDate(List<String> dateArray) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < dateArray.size(); i++) {
            Date date = format.parse(dateArray.get(i));
            dateList.add(date);
        }
        Collections.sort(dateList, new Comparator<Date>() {
            @Override
            public int compare(Date d1, Date d2) {
                return d2.compareTo(d1);
            }
        });
        Date result_date = dateList.get(0);
        String result = format.format(result_date);
        return result;
    }
}
